package com.cg.Interector;

import com.auth0.jwt.interfaces.DecodedJWT;

import com.cg.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
@Component
public class LoginIntorector implements HandlerInterceptor {
    @Resource
    private JwtUtil jwtConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        // Token 验证
        String token = request.getHeader("Authorization");
        try {
            // 校验成功放行请求
            DecodedJWT verifyToken = jwtConfig.verifyToken(token);
            return true;
        } catch (Exception e) {
            map.put("msg", "token验证失败: " + e);
        }
        // 校验失败返回失败信息
        String json = new ObjectMapper ().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(json);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
